package com.foolishbird.sdk.ui.assist;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.foolishbird.sdk.params.bean.AccountInfo;
import com.foolishbird.sdk.utils.ResUtils;

import java.util.ArrayList;
import java.util.List;


public class SpinnerListAdapter extends BaseAdapter implements View.OnClickListener{

    private List<AccountInfo> data = new ArrayList<AccountInfo>();
    private LayoutInflater inflater;

    private OnItemRemoveListener listener;

    public SpinnerListAdapter(List<AccountInfo> data) {
        if (data != null) {
            this.data.clear();
            this.data.addAll(data);
        }
    }

    public void setOnItemRemoveListener(OnItemRemoveListener listener) {
        this.listener = listener;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public AccountInfo getItem(int position) {
        return data.get(position);
    }

    public AccountInfo removeItem(int position){
        return data.remove(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HoldView holdView = null;
        if (convertView == null) {
            holdView = new HoldView();

            if (inflater == null) {
                inflater = LayoutInflater.from(parent.getContext());
            }

            final int resLayoutId = ResUtils.getLayoutIdentifier(parent.getContext(), "wan_adapter_login_spinner");
            final int resTitleId = ResUtils.getViewIdentifier(parent.getContext(), "login_dorpdown_item_title");
            final int resDeleteId = ResUtils.getViewIdentifier(parent.getContext(), "login_dorpdown_item_delete");

            convertView = inflater.inflate(resLayoutId, null);
            holdView.title = convertView.findViewById(resTitleId);
            holdView.delete = convertView.findViewById(resDeleteId);

            convertView.setTag(holdView);
        } else {
            holdView = (HoldView) convertView.getTag();
        }

        AccountInfo info = getItem(position);
        if(info != null){
            holdView.title.setText(info.getUsername());
            holdView.delete.setOnClickListener(this);
            holdView.delete.setTag(Integer.valueOf(position));
        }

        return convertView;
    }

    @Override
    public void onClick(View view) {
        Object object = view.getTag();
        if(object instanceof Integer){
            if(this.listener != null){
                this.listener.OnItemRemove(view, (int) object);
            }
        }
    }

    private class HoldView {
        private TextView title;
        private ImageButton delete;
    }

}
